import {asyncRoutes} from '@/router/index'
import store from '@/store/index'
import {formaterTree} from "@/utils/tools";
import {cloneDeep} from 'lodash'

/**
 * type 1目录 2按钮
 * @param menuPermissions 全部菜单按钮数据
 * @returns {{accessRoutes: [], sidebarList}}
 */
export function formatRouter(menuPermissions) {
    if (menuPermissions.length === 0) return
    console.time('start')
    const whiteList = ['order/orderDetails', 'product/productConfig', 'order', 'product']
    let permission = []
    const formatterMenuTree = (list) => {
        return list.filter(father => {
            const childArr = list.filter(child => father.id === child.parentId)
            if (childArr.length > 0) {
                if (father.type === 1 || father.webUrl) {
                    if (childArr[0].type === 2) {
                        // 如果子级第一位是按钮添加 permission 权限数组
                        permission = [
                            ...permission,
                            ...childArr
                        ]
                    }
                } else if (father.type === 2) {
                    // 按钮添加下级children
                    father.children = childArr
                }
            }
            // 返回携带webUrl 菜单
            return father.webUrl
        })
    }
    // 过滤所有菜单
    const filterMenu = formatterMenuTree(menuPermissions)

    /**
     * 返回过滤后的路由
     * @param routerMap 需要动态加载的路由
     * @returns {[]}
     */
    const filterRouter = (routerMap) => {
        let res = []
        routerMap.forEach(routes => {
            if (routes.children && routes.children.length) {
                routes.children = filterRouter(routes.children)
            }
            // 后台webUrl匹配前端路由
            const isRenderRoutes = filterMenu.find(item => {
                return item.webUrl === routes.meta.path
            })
            if (isRenderRoutes) {
                res.push({
                    ...routes,
                    meta: {
                        ...routes.meta,
                        title: isRenderRoutes.name,
                        sortNum: isRenderRoutes.orderNum,
                        icon: isRenderRoutes.icon,
                        webUrl: isRenderRoutes.webUrl,
                        id: isRenderRoutes.id
                    },
                })
            } else if (whiteList.indexOf(routes.meta.path) !== -1) {
                // 白名单路由直接返回
                res.push(routes)
            }
        })
        return res
    }
    // 深拷贝路由信息
    const deepRoutes = cloneDeep(asyncRoutes)
    const accessRoutes = filterRouter(deepRoutes)
    const menuList = formaterTree(filterMenu.filter(item => item.type === 1))
    const sidebar = menuList.sort((a, b) => {
        return a.sortNum - b.sortNum
    })
    store.commit('SET_AUTH', permission)
    store.commit('SET_MENULIST', sidebar)
    console.timeEnd('start')
    return {
        accessRoutes,
    }
}

